package wci.backend.interpreter.executors;

import static wci.intermediate.icodeimpl.ICodeNodeTypeImpl.TEST;

import java.util.List;

import wci.backend.interpreter.Executor;
import wci.intermediate.ICodeNode;
import wci.intermediate.icodeimpl.ICodeNodeTypeImpl;

/**
 * <h1>LoopExecutor</h1>
 * <p>执行循环语句，repeat/while/for</p>
 * <p>Copyright (c) 2009 by Ronald Mak</p>
 * <p>For instructional purposes only.  No warranties.</p>
 */
public class LoopExecutor extends StatementExecutor
{
    public LoopExecutor(Executor parent)
    {
        super(parent);
    }
    public Object execute(ICodeNode node)
    {
        boolean exitLoop = false;
        ICodeNode exprNode = null;
        List<ICodeNode> loopChildren = node.getChildren();
        //循环判别式
        ExpressionExecutor expressionExecutor = new ExpressionExecutor(this);
        //循环主体
        StatementExecutor statementExecutor = new StatementExecutor(this);
        //循环直到判别式估值为真即推出
        while (!exitLoop) {
            ++executionCount; //循环语句也算计数
            for (ICodeNode child : loopChildren) {
                ICodeNodeTypeImpl childType =
                                      (ICodeNodeTypeImpl) child.getType();
                //是否判别式节点？是就更新一下退出值
                if (childType == TEST) {
                    if (exprNode == null) {
                        exprNode = child.getChildren().get(0);
                    }
                    exitLoop = (Boolean) expressionExecutor.execute(exprNode);
                }
                else {
                    statementExecutor.execute(child);
                }
                if (exitLoop) {
                    break;
                }
            }
        }
        return null;
    }
}
